package indi.jp.project.demo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import indi.jp.project.core.entity.JsonResult;
import indi.jp.project.core.util.SerialUtil;
import indi.jp.project.demo.dao.FlowDisposeDAO;
import indi.jp.project.demo.service.FlowDisposeService;
import indi.jp.project.process.entity.FlowTask;
import indi.jp.project.process.entity.FlowTaskHistory;
import indi.jp.project.process.entity.FlowTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 实现
 *
 * @author jiangping
 * @date 2022/5/9
 */
@Service
public class FlowDisposeServiceImpl implements FlowDisposeService {

    @Resource
    private FlowDisposeDAO flowDisposeDAO;

    @Resource
    private SerialUtil serialUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult flowDispose() throws Exception {
        dealMaterialData();
        dealProjectInitiateData();
        dealContractData();
        dealFapiaoData();
        dealSuppliesData();
//        dealHistory();
        return JsonResult.success("操作成功");
    }

    // 立项申请数据
    private void dealProjectInitiateData() throws Exception {
        String tableName = FlowTypeEnum.PROJECT.getTableName();
        List<Map<String, String>> list = flowDisposeDAO.queryIds(tableName);
        String typeCode = FlowTypeEnum.PROJECT.getFlowType();
        String typeName = FlowTypeEnum.PROJECT.getFlowName();
        commonUtil(typeCode, typeName, list);
    }

    // 合同数据
    private void dealContractData() throws Exception {
        String tableName = FlowTypeEnum.CONTRACT.getTableName();
        List<Map<String, String>> list = flowDisposeDAO.queryIds(tableName);
        String typeCode = FlowTypeEnum.CONTRACT.getFlowType();
        String typeName = FlowTypeEnum.CONTRACT.getFlowName();
        commonUtil(typeCode, typeName, list);
    }

    // 发票数据
    private void dealFapiaoData() throws Exception {
        String tableName = FlowTypeEnum.FAPIAO.getTableName();
        List<Map<String, String>> list = flowDisposeDAO.queryIds(tableName);
        String typeCode = FlowTypeEnum.FAPIAO.getFlowType();
        String typeName = FlowTypeEnum.FAPIAO.getFlowName();
        commonUtil(typeCode, typeName, list);
    }

    private void dealSuppliesData() throws Exception {
        String tableName = FlowTypeEnum.SUPPLIES.getTableName();
        List<Map<String, String>> list = flowDisposeDAO.queryIds(tableName);
        String typeCode = FlowTypeEnum.SUPPLIES.getFlowType();
        String typeName = FlowTypeEnum.SUPPLIES.getFlowName();
        commonUtil(typeCode, typeName, list);
    }

    private void commonUtil(String typeCode, String typeName, List<Map<String, String>> list) throws SQLException {
        for (Map<String, String> map : list) {
            String taskId = map.get("id");
//            String checkUser = map.get("check_user");
//            JSONArray ja = JSONArray.parseArray(checkUser);
//            if (ja == null || ja.size() == 0) {
//                continue;
//            }
            List<FlowTask> flowList = new ArrayList<>();
            FlowTask start = generateBeginFlowTask(taskId, typeCode, typeName);
            flowList.add(start);
            FlowTask end = generateEndFlowTask(taskId, typeCode, typeName);
            flowList.add(end);
//            for (int i = 0; i < ja.size(); i++) {
//                JSONObject jo = ja.getJSONObject(i);
//                FlowTask flowTask = generateFlowTask(typeCode, typeName, i + 1, taskId, jo);
//                if (flowTask != null) {
//                    flowList.add(flowTask);
//                }
//            }
            flowDisposeDAO.insertBatchFlowTask(flowList);
        }
    }

    // 耗材数据
    private void dealMaterialData() throws Exception {
        List<Map<String, String>> list = flowDisposeDAO.queryMaterialFlowData();
        for (Map<String, String> map : list) {
            String taskId = map.get("id");
            String category = String.valueOf(map.get("category"));
            String typeCode = "";
            String typeName = "";
            if ("0".equals(category)) {
                typeCode = FlowTypeEnum.MATERIAL_PROD.getFlowType();
                typeName = FlowTypeEnum.MATERIAL_PROD.getFlowName();
            } else {
                typeCode = FlowTypeEnum.MATERIAL_WORK.getFlowType();
                typeName = FlowTypeEnum.MATERIAL_WORK.getFlowName();
            }
            List<FlowTask> flowList = new ArrayList<>();
            FlowTask start = generateBeginFlowTask(taskId, typeCode, typeName);
            flowList.add(start);
            FlowTask end = generateEndFlowTask(taskId, typeCode, typeName);
            flowList.add(end);
//            JSONArray ja = JSONArray.parseArray(checkUser);
//            for (int i = 0; i < ja.size(); i++) {
//                JSONObject jo = ja.getJSONObject(i);
//                FlowTask flowTask = generateFlowTask(typeCode, typeName, i + 1, taskId, jo);
//                if (flowTask != null) {
//                    flowList.add(flowTask);
//                }
//            }
            flowDisposeDAO.insertBatchFlowTask(flowList);

        }
    }

    private FlowTask generateBeginFlowTask(String taskId, String typeCode, String typeName) {
        FlowTask flowTask = new FlowTask();
        flowTask.setId(String.valueOf(serialUtil.nextId()));
        flowTask.setTaskId(taskId);
        flowTask.setTypeCode(typeCode);
        flowTask.setTypeName(typeName);
        flowTask.setName("新建");
        flowTask.setCategory(0);
        flowTask.setState(0);
        flowTask.setStateName("新建");
        flowTask.setRequired(false);
        return flowTask;
    }

    private FlowTask generateEndFlowTask(String taskId, String typeCode, String typeName) {
        FlowTask flowTask = new FlowTask();
        flowTask.setId(String.valueOf(serialUtil.nextId()));
        flowTask.setTaskId(taskId);
        flowTask.setTypeCode(typeCode);
        flowTask.setTypeName(typeName);
        flowTask.setName("审批完成");
        flowTask.setCategory(0);
        flowTask.setState(99);
        flowTask.setStateName("审批完成");
        flowTask.setRequired(false);
        return flowTask;
    }

    private FlowTask generateFlowTask(String typeCode, String typeName, int state, String taskId, JSONObject jo) {
        String roleCode = jo.getString("node");
        String handler = jo.getString("checkUser");
        String handlerName = jo.getString("checkName");
        if (StringUtils.isBlank(roleCode) || StringUtils.isBlank(handler) || StringUtils.isBlank(handlerName)) {
            return null;
        }

        FlowTask flowTask = new FlowTask();
        flowTask.setId(String.valueOf(serialUtil.nextId()));
        flowTask.setTypeCode(typeCode);
        flowTask.setTypeName(typeName);
        flowTask.setTaskId(taskId);
        flowTask.setCategory(2);
        flowTask.setName(roleCode);
        flowTask.setState(state);
        flowTask.setStateName("待定");
        flowTask.setRoleCode(roleCode);
        flowTask.setRoleName("待定");
        flowTask.setHandler(handler);
        flowTask.setHandlerName(handlerName);
        return flowTask;
    }

    private void dealHistory() throws SQLException, ParseException {
        List<Map<String, String>> list = flowDisposeDAO.queryOldHistory();
        List<FlowTaskHistory> history = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, String> map = list.get(i);
            FlowTaskHistory entity = new FlowTaskHistory();
            entity.setId(String.valueOf(serialUtil.nextId()));
            entity.setTaskId(map.get("task_id"));
            entity.setNodeName(map.get("node_name"));
            entity.setState(98);
            entity.setStateName("无");
            String dealType = map.get("deal_type");
            if ("开启".equals(dealType)) {
                entity.setOperation("提交");
            } else if ("通过".equals(dealType)) {
                entity.setOperation("agree");
            } else if ("回退".equals(dealType)) {
                entity.setOperation("reject");
            } else if ("作废".equals(dealType)) {
                entity.setOperation("cancel");
            } else {
                entity.setOperation("unknown");
            }
            entity.setOpinion(map.get("remark"));
            entity.setHandler(map.get("check_user") == null ? "unknown" : map.get("check_user"));
            entity.setHandlerName("待定");
            entity.setCreateBy(map.get("check_user") == null ? "unknown" : map.get("check_user"));
            Date createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(map.get("start_time"));
            entity.setCreateTime(createTime);
            history.add(entity);
            if (i % 200 == 0 || i == list.size() - 1) {
                flowDisposeDAO.insertBatchFlowHistory(history);
                history = new ArrayList<>();
            }
        }
    }
}
